# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :comments.py
# @Time      :2022/6/6 0006 13:59
# @Author    :何胜利

from flask import Blueprint, jsonify, g
from flask_restful import Api, Resource, marshal, reqparse
import json

from common.model_fields.user import *
from common.utils.login_utils import login_required
from models import db
from models.user import Comment, UserModel, News

comment_bp = Blueprint("comment_bp", __name__, url_prefix="/comments")

api = Api(comment_bp)


class CommentResource(Resource):
    # @login_required
    # def get(self, nid):
    #     """
    #     :param nid:
    #     :return:
    #     返回的数据格式
    #     {
    #         "nid":nid,
    #         'comments':[
    #             {
    #                 "cid": 1,
    #                 "content": '我冲突皮哦按来的',
    #                 'user_info":{
    #                     'uid':1,
    #                     'name':'张三',
    #                     'img':''
    #                 },
    #                 "child_comments":[
    #                     {
    #                         "cid": 1,
    #                         "content": '我冲突皮哦按来的',
    #                         'user_info":{
    #                             'uid':1,
    #                             'name':'张三',
    #                             'img':''
    #                         },
    #                     },
    #                     ....
    #                 ]
    #             }
    #             .....
    #         ]
    #
    #     }
    #     """
    #
    #     # 根据文章id 获取文章信息
    #     comments = Comment.query.filter_by(article_id=nid).all()
    #     # 判断文章是否存在
    #     if not comments:
    #         # 不存在 返回空
    #         return jsonify(message="获取评论成功", data=[], code=200)
    #     else:
    #         # 存在  获取评论的用户id 然后获取用户信息
    #         comments_dict = json.loads(json.dumps(marshal(comments, comments_fields)))
    #         print("评论的字典数据", comments_dict)
    #         for comment in comments_dict:
    #             user = UserModel.query.filter_by(uid=comment["user_id"]).first()
    #             comment["user"] = {
    #                 "uid": user.uid,
    #                 "user_name": user.user_name,
    #                 "profile_photo": user.profile_photo,
    #             }
    #             # 判断文章是否有回复
    #             is_reply_comment = comment["parent_id"]
    #
    #             if is_reply_comment:
    #                 # 有回复
    #                 # 获取回复的评论内容即哦那个和信息
    #                 comments = Comment.query.filter_by(cmid=comment["parent_id"]).all()
    #                 comments_dict = json.loads(json.dumps(marshal(comments, comments_fields)))
    #                 for comment in comments_dict:
    #                     user = UserModel.query.filter_by(uid=comment["user_id"]).first()
    #                     comment["user"] = {
    #                         "uid": user.uid,
    #                         "user_name": user.user_name,
    #                         "profile_photo": user.profile_photo,
    #                     }
    #             return jsonify()
    #         print("包含用户信息的评论内容", comments_dict)
    #         return jsonify(message="获取评论成功", code=200, data=comments_dict)
    @login_required
    # 获取评论信息
    def get(self, nid):
        # 根据文章id 获取文章的   第一级评论
        comment1 = Comment.query.filter_by(article_id=nid, parent_id=None).all()
        # 根据一级评论 获取二级评论   子评论
        comment_list = []
        for i in comment1:
            # 序列化每一个一级评论
            comment_ = marshal(i, comments_fields)
            # 获取所有二级评论
            comment2 = Comment.query.filter_by(parent_id=i.cmid).all()
            # 获取每一个一级评论的用户信息
            user1 = UserModel.query.filter_by(uid=i.user_id).first()
            comment2_list = []
            for j in comment2:
                # 获取二级评论的用户信息
                user = UserModel.query.filter_by(uid=j.user_id).first()
                # 序列化每一个二级评论
                comment2 = marshal(j, comments_fields)
                # 序列化每一个用户信息
                comment2['user'] = marshal(user, user_fields)
                comment2_list.append(comment2)
            # comment_['parent'] = comment2  # 二级评论信息赋值 parent
            comment_['parent'] = comment2_list
            comment_['user'] = marshal(user1, user_fields)  # 一级用户信息  赋值给一级评论  user里
            comment_list.append(comment_)
        return jsonify(message="获取成功", code=200, data=comment_list)
    # @login_required
    # def get(self, nid):
    #     # 获取所有的评论
    #     # 1，接收前端传来的文章id
    #     comment1 = Comment.query.filter_by(article_id=nid, parent_id=None).all()
    #     if not comment1:
    #           return jsonify(message='暂时还没有评论', code=200, data=[])
    #     # 有评论,把有序字段转成字典
    #     comments_dict1 = json.loads(json.dumps(marshal(comment1, comments_fields)))
    #     for comment1 in comments_dict1:
    #         # 获取评论的用户id，获取用户信息
    #         user = UserModel.query.filter_by(uid=comment1['user_id']).first()
    #         comment1['user'] = {
    #             'uid': user.uid,
    #             'uname': user.user_name,
    #             'profile_photo': user.profile_photo
    #         }
    #         comments2_list = []
    #         comments2 = Comment.query.filter_by(parent_id=comment1['cmid']).all()
    #         comments_dict2 = json.loads(json.dumps(marshal(comments2, comments_fields)))
    #         for comment2 in comments_dict2:
    #             # 获取评论的用户id，获取用户信息
    #             user = UserModel.query.filter_by(uid=comment2['user_id']).first()
    #             comment2['user'] = {
    #                 'uid': user.uid,
    #                 'uname': user.user_name,
    #                 'profile_photo': user.profile_photo
    #             }
    #             comments2_list.append(comment2)
    #
    #         comment1["parent"] = comments2_list
    #     return jsonify(message='获取评论成功', code=200, data=comments_dict1)

    @login_required
    # # 发布评论
    def post(self, nid):
        uid = g.user_id
        parser = reqparse.RequestParser()
        parser.add_argument("content")
        parser.add_argument("parent_id")
        args = parser.parse_args()
        content = args["content"]
        parent_id = args["parent_id"]
        news = News.query.filter_by(nid=nid).first()

        if news:
            if parent_id:
                resp = Comment(user_id=uid, article_id=nid, parent_id=parent_id, content=content)
                db.session.add(resp)
                db.session.commit()
                return jsonify(message="评论成功", code=200)
            else:
                resp = Comment(user_id=uid, article_id=nid, parent_id=None, content=content)
                db.session.add(resp)
                db.session.commit()
                return jsonify(message="评论成功", code=200)


class NewsAddGet(Resource):
    def get(self):
        news = News.query.all()
        return marshal(news, news_fields)

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument("user_id")
        parser.add_argument("channel_id")
        parser.add_argument("title")
        parser.add_argument("cover")
        parser.add_argument("ctime")
        parser.add_argument("reviewer_id")
        parser.add_argument("delete_time")
        parser.add_argument("reject_reason")
        parser.add_argument("content")
        args = parser.parse_args()
        user_id = args["user_id"]
        channel_id = args["channel_id"]
        title = args["title"]
        cover = args["cover"]
        ctime = args["ctime"]
        reviewer_id = args["reviewer_id"]
        delete_time = args["delete_time"]
        reject_reason = args["reject_reason"]
        content = args["content"]
        news = News(user_id=user_id, channel_id=channel_id, title=title, cover=cover,
                    ctime=ctime, reviewer_id=reviewer_id, delete_time=delete_time,
                    reject_reason=reject_reason, content=content)
        db.session.add(news)
        db.session.commit()
        return jsonify(message="添加文章成功", code=200)

    def put(self):
        parser = reqparse.RequestParser()
        parser.add_argument("content")
        parser.add_argument("user_id")
        args = parser.parse_args()
        content = args["content"]
        user_id = args["user_id"]
        News.query.filter_by(user_id=user_id).update({"content": content})
        db.session.commit()
        return jsonify(message="修改贴文内容成功", code=200)

    def delete(self):
        parser = reqparse.RequestParser()
        parser.add_argument("user_id")
        args = parser.parse_args()
        user_id = args["user_id"]
        News.query.filter_by(user_id=user_id).delete()
        db.session.commit()
        return jsonify(message="删除文章成功", code=200)


api.add_resource(NewsAddGet, "/addget")
api.add_resource(CommentResource, "/all_release/<int:nid>")
